/**
  * Copyright (c) CSIRO Australia, 2009
  *
  * @author $Author: jia020 $
  * @version $Id: PDQueryServiceImpl.java 643 2009-05-20 00:20:55Z jia020 $
  */
package au.csiro.nt.pdsp.server;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import au.csiro.nt.pdsp.register.Login;
import au.csiro.nt.pdsp.register.RegisterException;
import au.csiro.nt.pdsp.register.UserManager;
import au.csiro.nt.pdsp.client.PDQueryService;
import au.csiro.nt.pdsp.ims.IMSManager;
import au.csiro.nt.pdsp.util.Base64Coder;
import au.csiro.nt.pdsp.workflow.TimerThread;
import au.csiro.nt.pdsp.workflow.WorkflowException;
import au.csiro.nt.pdsp.workflow.WorkflowTask;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class PDQueryServiceImpl extends RemoteServiceServlet implements	PDQueryService {
	private HashMap sessionMap = new HashMap<String,String>();
	/**
	 * 
	 */
	public PDQueryServiceImpl() {
		super();
		TimerThread timerThread = new TimerThread();	
	}
	public 	boolean subscribePDSP(String username,boolean subscribe) {
		UserManager userManager = new UserManager();
		return userManager.subscribePDSP(username, subscribe);
	}
	public String login(String username,String password){
		Login login = new Login();
		String params = login.verifyPassword(username, password);
		String sessionID;
		if (params != null) {
			HttpServletRequest request = this.getThreadLocalRequest();
			HttpSession httpSession = request.getSession( true );	
			int hashCode =  (login == null) ? 0 : login.hashCode();
			sessionID = Integer.toHexString(hashCode);
			httpSession.setAttribute( "sessionid", sessionID);		
			sessionMap.put(sessionID, params);
			System.out.println(sessionID);
		}
		return params;		
	}	
//  HttpServletRequest request = this.getThreadLocalRequest();
//  HttpSession session =request.getSession();
	public boolean reviewWorkflow(int workflowid){
		WorkflowTask task = new WorkflowTask();		
		return task.reviewWorkflow(workflowid);
	}
	public String getUnreviewedWorkflows() {
		WorkflowTask task = new WorkflowTask();				
		return task.createXMLUnreviewedWorkflows();
	}
	public 	String getWorkflows(int type,int param) {
		WorkflowTask task = new WorkflowTask();
		return task.createXMLWorkflows(type,param);
	}
	public String getMyTasks(String userid) {	   
		HttpServletRequest request = this.getThreadLocalRequest();
		HttpSession httpSession = request.getSession( true );		

		String sessionID = (String)httpSession.getAttribute("sessionid");			
		System.out.println(sessionID);
		String params = (String) sessionMap.get(sessionID);
		WorkflowTask task = new WorkflowTask();		
		return task.createXMLTasks(userid);
	}
	public String getMyWorkflows(int taskid) {
		WorkflowTask task = new WorkflowTask();
		return task.createXMLWorkflows(taskid);
	}
	
	public boolean saveTask(String userid,String taskBase64,String description) {
		boolean ret = false;
		String task = Base64Coder.decodeString(taskBase64);
		WorkflowTask taskManager = new WorkflowTask();
		int taskId = 0;
		try {
			taskId = taskManager.newTask(userid,task,description);
		} catch (WorkflowException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		
		return (taskId > 0);
	}
	public String queryServer(Map formData) {
//		sql = constructSQL(formData);
	//	ArrayList<MetaItem<String,String>> columns = new ArrayList();
		StringBuffer result = new StringBuffer();
		boolean bCommaResult = false;
		StringBuffer criteria = new StringBuffer();
		boolean bCommaCriteria = false;
		String value, key;
		value = (String) formData.get("Rbasic");
		if (value!=null && value.equalsIgnoreCase("on")) {
			if (bCommaResult)
				result.append(',');
			result.append("centrelinkid,driverid,firstname,lastname,birthday,martial");
			bCommaResult = true;
		}
		value = (String) formData.get("Rcontact");
		if (value!=null && value.equalsIgnoreCase("on")) {
			if (bCommaResult)
				result.append(',');
			result.append("residentialaddress,suburb,postcode,phone,mobile,email");
			bCommaResult = true;

		}
		value = (String) formData.get("Rfinancial");
		if (value!=null && value.equalsIgnoreCase("on")) {
			if (bCommaResult)
				result.append(',');
			result.append("income,assetvalue");
			bCommaResult = true;

		}
		value = (String) formData.get("Rmedical");
		if (value!=null && value.equalsIgnoreCase("on")) {
			if (bCommaResult)
				result.append(',');
			result.append("healthy");
			bCommaResult = true;

		}
		value = (String) formData.get("Rothers");
		if (value!=null && value.equalsIgnoreCase("on")) {
			if (bCommaResult)
				result.append(',');
			result.append("helplog");	
			bCommaResult = true;

		}
		value = (String) formData.get("Cfirstname");
		if (value != null) {
			if (bCommaCriteria)
				criteria.append(" and ");
			criteria.append("firstname='");
			criteria.append(value);
			criteria.append('\'');
			bCommaCriteria = true;

		}
		value = (String) formData.get("Clastname");
		if (value != null) {
			if (bCommaCriteria)
				criteria.append(" and ");
			criteria.append("lastname='");
			criteria.append(value);
			criteria.append('\'');
			bCommaCriteria = true;

		}
		value = (String) formData.get("Cbirthday");
		if (value != null) {// <birthday
			if (bCommaCriteria)
				criteria.append(" and ");
			criteria.append("birthday <'");	
			criteria.append(value);
			criteria.append('\'');
			bCommaCriteria = true;
		}
		value = (String) formData.get("Csuburb");
		if (value != null) {
			if (bCommaCriteria)
				criteria.append(" and ");
			criteria.append("suburb='");
			criteria.append(value);
			criteria.append('\'');
			bCommaCriteria = true;

		}
		value = (String) formData.get("Cmartial");
		if (value != null) {
			if (bCommaCriteria)
				criteria.append(" and ");
			criteria.append("martial='");
			criteria.append(value);
			criteria.append('\'');
			bCommaCriteria = true;

		}
		value = (String) formData.get("Cincome");
		if (value != null) {// <income
			if (bCommaCriteria)
				criteria.append(" and ");
			criteria.append("income<");
			criteria.append(value);
			bCommaCriteria = true;

		}
		value = (String) formData.get("Cassetvalue");
		if (value != null) {// <assetvalue
			if (bCommaCriteria)
				criteria.append(" and ");
			criteria.append("assetvalue<");
			criteria.append(value);
			bCommaCriteria = true;
		}
		String sql = "select " + result.toString() + " from privacydata where "	+ criteria.toString();
		String sqlSample = "select " + result.toString() + " from privacydata where centrelinkid = 'sample'";
		WorkflowTask task = new WorkflowTask();
		return task.createXMLWorkflowsSample(sql,sqlSample);
	}
	@Override
	public String getMyMessages(String userid) {		
		return IMSManager.createXMLMyPendingMessages(userid);
	}
	@Override
	public
	boolean sendMessage(int imsID, String message) {
		return IMSManager.recvMessage(imsID, message);
	}
}
